package com.hqumath.keyboard;

import android.app.Activity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;



import java.lang.reflect.Method;


/**
 * ****************************************************************
 * 文件名称: KeyboardUtil
 * 作    者: Created by gyd
 * 创建时间: 2018/11/29 14:03
 * 文件描述: 键盘工具类
 * 注意事项:
 * ****************************************************************
 */
public class KeyboardUtil {
    private final TextView btnConfirm;
    private final TextView tvAlreadyInput;
    private final EditText etContent;
    private final ImageView ivEye;
    private final ImageView vBackIv;
    private Activity mActivity;
    private View mParent;
    LinearLayout mIncludeKeyboardview;
    LinearLayout llInputNum;
    private PopupWindow mWindow;
    private MyKeyboardView mKeyboardView;
    private boolean needInit;
    private boolean mScrollTo = false;//是否界面上移，适应键盘
//    private int mEditTextHeight;//编辑框高度 44dp
    private int mKeyboardHeight;//键盘高度 260dp
    private int mHeightPixels;//屏幕高度
    private int mKeyBoardMarginEditTextTopHeight;//键盘距离编辑框顶部最少距离 （用来计算键盘上推高度）
    private boolean isShow=false;//默认不显示密码

    private boolean isLimit=false;//指定字符长度
    private boolean isVisible=false;//是否显示输入的字符长度



    private static int minLength=1;//isLimit=false就是最小长度，true就是可输入最大长度
    public KeyboardUtil(Activity context) {
        this.mActivity = context;
//        this.mParent = parent;
        //获取xml布局文件

        mIncludeKeyboardview = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.common_keyboardview, null);
        //获取输入框及按钮的布局
//        LinearLayout mKeyboardTopView = (LinearLayout) mIncludeKeyboardview.findViewById(R.id.keyboard_top_rl);
        btnConfirm =(TextView) mIncludeKeyboardview.findViewById(R.id.btn_confirm);
        tvAlreadyInput =(TextView) mIncludeKeyboardview.findViewById(R.id.tvAlreadyInput);
        llInputNum =(LinearLayout) mIncludeKeyboardview.findViewById(R.id.llInputNum);
        btnConfirm.setEnabled(false);
        etContent=(EditText)  mIncludeKeyboardview.findViewById(R.id.edt_number);
        ivEye=(ImageView)  mIncludeKeyboardview.findViewById(R.id.img_eye);
        vBackIv=(ImageView)  mIncludeKeyboardview.findViewById(R.id.vBackIv);
        //键盘的viewId
//        mWindow= new KeyBoardPop(mActivity);
        mKeyboardView = (MyKeyboardView) mIncludeKeyboardview.findViewById(R.id.keyboard_view);
        //创建了一个popwindow，这个是键盘的父控件
        mWindow = new PopupWindow(mIncludeKeyboardview, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, false);
//        mWindow = new PopupWindow(mActivity);
        // 设置宽高为 MATCH_PARENT
        mWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mWindow.setContentView(mIncludeKeyboardview);
//        BasePopupWindow basePopupWindow = new BasePopupWindow(mActivity);
        mWindow.setAnimationStyle(R.style.AnimBottom);   //滑出滑入动画
        mWindow.setOnDismissListener(mOnDismissListener);
        mWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);//防止被底部工具栏遮挡
        int mEditTextHeight = dp2px(44);//44dp 编辑框高度
        mKeyboardHeight = dp2px(260);//260dp
//        mKeyBoardMarginEditTextTopHeight = mEditTextHeight * 2;
        mHeightPixels = context.getResources().getDisplayMetrics().heightPixels;

        //点击键盘完成按钮隐藏
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String pwd = etContent.getText().toString();
//                if (pwd.length() < 8) {
//                    UtilsKt.showToast(context.getString(R.string.common_insufficient_password_length), Toast.LENGTH_SHORT,Gravity.CENTER);
//                    return;
//                }
                if (onConnectBtnClickListener!=null){
                    onConnectBtnClickListener.onOnConnectBtnClick(etContent.getText().toString());
                }
                //回调触发wifi连接
                hide();
                etContent.setText("");
            }
        });

        ivEye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etContent.setTransformationMethod(isShow ? PasswordTransformationMethod.getInstance() : HideReturnsTransformationMethod.getInstance());
                etContent.setSelection(etContent.getText().toString().length());
                isShow = !isShow;
            }
        });

        vBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hide();
                etContent.setText("");
            }
        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if (TextUtils.isEmpty(charSequence.toString())||charSequence.length()<minLength) {
                    btnConfirm.setEnabled(false);
                    btnConfirm.setBackground(mActivity.getDrawable(R.drawable.edit_btn_shape));
                } else {
                    btnConfirm.setEnabled(true);
                    btnConfirm.setBackground(mActivity.getDrawable(R.drawable.comm_btn_blue_6_corner));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                tvAlreadyInput.setText(String.valueOf(editable.length()));
            }
        });
    }

    /**
     * 设置输入框提示文本
     * */
    public void setEditTextHint(String hint){
        etContent.setHint(hint);
    }

    public void setEditTextHintAndMinLength(String hint,int length,boolean limit,boolean visible){
        isLimit=limit;//true是限制字符，length就是最大长度，false的话lenght就是最小长度
        isVisible=visible;
        if (isLimit){
            InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(length);
            etContent.setFilters(new InputFilter[]{ lengthFilter });
        }
        if (visible){
            //这里默认给了20个字符，展示已经输入的字符长度，可以根据自己的需求更改
            InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(20);
            etContent.setFilters(new InputFilter[]{ lengthFilter });
            //显示输入的字符长度数字
            llInputNum.setVisibility(View.VISIBLE);
        }else{
            llInputNum.setVisibility(View.INVISIBLE);
        }

        etContent.setHint(hint);
        minLength=length;

    }

    /**
     * 键盘初始化，
     */

    //传递进来类型及输入框
    public void initKeyboard(final int keyBoardType) {
        show(keyBoardType);
    }
    /**
     * 设置不需要使用这个键盘的edittext,解决切换问题
     *
     * @param edittexts
     */
    @SuppressWarnings("all")
    public void setOtherEdittext(EditText... editTexts) {
        for (EditText editText : editTexts) {
            editText.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        //防止没有隐藏键盘的情况出现    new Handler().postDelayed(new Runnable())
                        hide();
                    }
                    return false;
                }
            });
        }
    }

    /**
     * 当点击了输入框，传递输入框及键盘类型
     * */
    public void show(int keyBoardType){
        //显示自定义键盘
        if (mWindow != null && !mWindow.isShowing())
            mWindow.showAtLocation(mActivity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        //隐藏系统
        KeyboardTool.hideInputForce(mActivity,etContent);
        //设置可焦
        etContent.setFocusable(true);
        //触摸效果获取焦点
        etContent.setFocusableInTouchMode(true);
        //获取焦点
        etContent.requestFocus();
        mKeyboardView.init(etContent, mWindow, keyBoardType);
    }

    public boolean hide() {
        if (mWindow != null && mWindow.isShowing()) {
            mWindow.dismiss();
//            needInit = true;
            return true;
        }
        return false;
    }

    /**
     * 隐藏系统键盘
     *
     * @param editText
     */
    private static void hideSystemSofeKeyboard(EditText editText) {
        //SDK_INT >= 11
        try {
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(editText, false);
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int dp2px(float dpValue) {
        float scale = mActivity.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    //键盘消失，还原父控件位置
    private PopupWindow.OnDismissListener mOnDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            if (mScrollTo) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mScrollTo = false;
                        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mParent.getLayoutParams();
                        lp.topMargin = 0;
                        mParent.setLayoutParams(lp);
                    }
                });
            }
        }
    };

    //键盘距离编辑框顶部最少高度
    public void setKeyBoardMarginEditTextTopHeight(int mKeyBoardMarginEditTextTopHeight){
        this.mKeyBoardMarginEditTextTopHeight = mKeyBoardMarginEditTextTopHeight;
    }

    private OnConnectBtnClickListener onConnectBtnClickListener;

    public void setOnConnectBtnClickListener(OnConnectBtnClickListener onConnectBtnClickListener) {
        this.onConnectBtnClickListener = onConnectBtnClickListener;
    }

    public interface OnConnectBtnClickListener {
        void onOnConnectBtnClick(String content);
    }
}
